<script>
	import mqttRequest from '@/utils/mqtt/mqtt.js';
	const {
		Api
	} = require('@/utils/api/api.js');
	const {
		xm_uuid,
		xm_appKey,
		xm_appMiYao,
		xm_movedCard,
		appletIdentify
	} = require('@/app.config.js');
	const {
		BaseURL,
		version
	} = require('@/utils/api/baseUrl.js')
	const {generateRandomString} = require('@/utils/util.js');
	export default {
		data() {
			return {
				path: null
			};
		},
		onLaunch(ev) {
			if (!uni.getStorageSync('openId')) {
				console.log('没有openId')
				let clientId =  generateRandomString(24);
				uni.setStorageSync('openId',clientId);
			}
			uni.setStorageSync('isOfficialAccounts', true);
			this.path = ev.path
			this.autoUpdate();
			uni.setStorageSync("adddevice", 0);
			// #ifndef H5 || APP || MP-ALIPAY || MP-JD
			this.checkCache()
			// #endif
			// this.watch()
			let data = wx.getLaunchOptionsSync()
			if (data.scene == 1043) {
				// uni.reLaunch({
				// 	url:'jvss/pagesMine/about/about'
				// })
			}
			// this.$logs({info:'小程序重新进入-onLaunch'})
			console.log(this.globalData,'this.globalData')
		},
		onShow() {
            uni.setTabBarItem({
                index: 0,
                text: this.$t('General.home.device'),
            })
            uni.setTabBarItem({
                index: 1,
                text: this.$t('General.mine.my')
            })
			if (!uni.getStorageSync('openId')) {
				console.log('没有openId')
				let clientId =  generateRandomString(24);
				uni.setStorageSync('openId',clientId);
			}
			this.$logs({info:'小程序进入查看openId',openId:uni.getStorageSync('openId')})
			uni.setStorageSync('appIsShow',true)
			this.$logs({info:'小程序重新进入-onShow'})
			this.globalData.mqtt = new mqttRequest();
			const accessToken = uni.getStorageSync('accessToken') || '';
			const userInfo = uni.getStorageSync('userInfo') || {};
			// mqtt连接
			if (accessToken !== '' && Object.keys(userInfo).length > 0) {
				setTimeout(() => {
					this.globalData.mqtt.createConnect()
                    uni.removeStorageSync('mqttCloseTemp')
				}, 100)
			}
			// 埋点数据
			// #ifdef MP-WEIXIN
			this.interval = setInterval(() => {
				this.getPoint()
			}, 10000);
			// #endif
			setTimeout(()=>{
				// this.getPointquery()
				// this.getpointQueryClass()
			},2000)
		},
		onHide() {
			if(this.interval){
				clearInterval(this.interval)
			}
			// this.deviceLogOut()
			uni.$emit('appLogout', {
				isAppLogout: true,
			})
			clearInterval(getApp().globalData.keepTimer);
			getApp().globalData.keepTimer = null
			if(getApp().globalData.mqtt.client){
				getApp().globalData.mqtt.close()
                // 记录断链时间戳
                var temp = Date.now()
                uni.setStorageSync('mqttCloseTemp', temp)
			}
			let pages = getCurrentPages()
			if (pages.length > 0) {
				if (pages[pages.length - 1].$page.fullPath.includes('live-lexin') || pages[pages.length - 1].$page.fullPath
					.includes('live1') || pages[pages.length - 1].$page.fullPath.includes('live/live') || pages[pages.length - 1].$page.fullPath.includes('doorLockHome')) {
					uni.switchTab({
						url: '/jvss/pages/device/home'
					})
				}
                if(pages[pages.length-1].route.includes('/doorbellCall')) {
                    uni.navigateBack({})
                }
                console.log('页面隐藏时页面栈的信息', pages)
			}
            console.log('页面隐藏时页面栈的信息', pages)
			uni.setStorageSync('isOnWebsocket',false)
			uni.setStorageSync('isSendWebsocket',false)
			this.$logs({info:'小程序切换到后台-onHide',currentPages:pages,temp})
		},
		onError() {},
		// watch(){
		//   let value = this.globalData.globalText
		//   Object.defineProperty(this.globalData,'globalText',{
		//     configurable:true,
		//     enumerable:true,
		//     set:(newValue)=>{
		//       console.log('##########################',newValue);
		//       value = newValue
		//     },

		//     get:()=>{
		//       console.log('**************************',value);
		//       return value
		//     }
		//   })
		// },
		globalData: {
			// globalText:1,
			api: new Api(xm_uuid, xm_appKey, xm_appMiYao, xm_movedCard),
			// api接口对象
			constant: require('utils/constant'),
			//常量
			appConfig: require('./app.config'),
			//配置
			utils: require('utils/util'),
			//工具
			aes: require('utils/aes'),
			//aes加密
			// icon图标连接
			iconUrl: BaseURL+'/sceneIcon/changeIconByColor',
			errCodeMsg: require('utils/errorCode.js'),
			deviceToken: '',
			keepTimer: null,
			// #ifdef MP-WEIXIN
			logger: wx.getRealtimeLogManager(),
			logManager: wx.getLogManager({
				level: 1
			}),
			// #endif
			version: version,
			mqtt:'',
			appletIdentify:appletIdentify,
			generalIdentify:'jlink',//通用标识
			
		},
		methods: {
			getPoint() {
				let el = uni.getStorageSync('tabEvent') || [];
				// console.log(el,'el数据')
				if(el.length == 0) return
				let data = {
					app: "Jlink小程序",
					appKey: xm_appKey,
					el,
					os: "weChat",
					t: Math.floor(Date.now() / 1000),
					uuid: xm_uuid,
					vc: "666666",
					vn: getApp().globalData.version
				}
				// console.log(data, '传参')
				getApp().globalData.api.pointUpload(data, (result) => {
					// console.log(result, '埋点数据');
					uni.setStorageSync('tabEvent',[])
				})
			},
			getPointquery() {
				let data = {
					page: 1,
					psize: 99,
					filter:{
						uuid: xm_uuid,
					}
				}
				getApp().globalData.api.pointQuery(data, (result) => {
					console.log(result, '查询埋点数据');
				})
			},
			getpointQueryClass() {
				// ,'400114','400115'
				console.log('看见哎会收到空晋安河谁看得见哈斯柯达')
				let data = {
					page: 1,
					psize: 99,
					filter:{
						ec:['600014'],
						// s:1700496000,
						s:1702396800,
						e:1702483199,
						appKey:xm_appKey
					}
				}
				getApp().globalData.api.pointQueryClass(data, (result) => {
					console.log(result, '查询埋点分类数据');
				})
			},
			websocketInfo(res) {
				// console.log('APP.vue 界面接收 mqtt消息', JSON.parse(res));
				let info = JSON.parse(res)
			},
			// 设备退出登录
			deviceLogOut() {
				let token = uni.getStorageSync('deviceToken') || getApp().globalData.deviceToken
				let data = {
					Name: 'Logout',
				};
				getApp().globalData.api.deviceLogOut(data, token, (result) => {
					this.$logs({
						info: '切换到后台退出登录',
						timer: getApp().globalData.keepTimer
					})
				});
			},
			// 赋值、创建、同步 scene 的某一个或多个属性
			syncScene(app, options) {
				let scene = uni.getStorageSync('scene');
				Object.keys(options).forEach((item) => {
					Object.keys(scene).forEach((pro) => {
						if (item === pro) {
							scene[pro] = options[item];
						} else {
							app[item] = options[item];
						}
					});
				});
				uni.setStorageSync('scene', scene);
			},
			// 检查缓存（登录）
			checkCache() {
				let currentTime = new Date().getTime()
				if (uni.getStorageSync('lastLoginTime')) {
					let time = uni.getStorageSync('lastLoginTime')
					if ((time + 30 * 24 * 60 * 60 * 1000) < currentTime) {
						// uni.removeStorageSync('accessToken');
						uni.setStorageSync('isOfficialAccounts', false) //判断是否显示绑定公众号弹窗
						uni.showModal({
							title: '提示',
							content: '登录已过期,请重新登录！',
							showCancel: false,
							success: (res) => {
								uni.removeStorageSync('userInfo');
								uni.removeStorageSync('checkAutoLogin');
								uni.reLaunch({
									url: '/jvss/pages/login/login'
								});
								uni.setStorageSync('lastLoginTime', currentTime)
							}
						});

						// #ifdef MP-WEIXIN
						this.$logs({
							loginExpired: '登录已过期'
						}, 'error')
						// #endif
						return
					}
				} else {
					uni.setStorageSync('lastLoginTime', currentTime)
				}
				uni.checkSession({
					success: (res) => {
						if (res.errMsg === 'checkSession:ok') {
							const accessToken = uni.getStorageSync('accessToken') || '';
							const userInfo = uni.getStorageSync('userInfo') || {};
							if (accessToken !== '' && Object.keys(userInfo).length > 0) {
								if (this.path != 'jvss/pagesDevice/share/share') {
									let data = wx.getLaunchOptionsSync()
									if (data.scene == 1043) {
										// data.path =data.path+'?data='+ '%7B%22adminToken%22%3A%22Ffbw%2FcDagD75EU8HYHMy7kxqBngyaelqozPLKDZe9lw%3D%22%2C%22alarmEvent%22%3A%22DoorLockCall%22%2C%22alarmId%22%3A%22230925154701272%22%2C%22date%22%3A%221695608138%22%2C%22devPassWord%22%3A%22%22%2C%22devUserName%22%3A%22admin%22%2C%22deviceName%22%3A%22%E6%B5%8B%E8%AF%95%E5%90%8D%E7%A7%B0%22%2C%22deviceNo%22%3A%2210000093761092843328%22%2C%22SerialNumber%22%3A%2210000093761092843328%22%2C%22AlarmID%22%3A%22230925154701272%22%7D'
										this.$logs({
											info: '公众号跳转App.vue-1043',
											data: data
										}, 'error')
										// uni.reLaunch({
										// 	url: '/' + data.path
										// });
									} else {
										// uni.reLaunch({
										//     url: '/jvss/pages/device/home'
										// });
									}
								}
							} else {
								this.toLogin()
							}
						} else {
							this.toLogin()
						}
					}
				})
			},
			// 跳转到登录
			toLogin() {
				uni.setStorageSync('isToken', true);
				uni.reLaunch({
					url: '/jvss/pages/login/login'
				});
			},
			// 自动更新
			autoUpdate() {
				let self = this;
				if (uni.canIUse('getUpdateManager')) {
					const updateManager = uni.getUpdateManager();
					updateManager.onCheckForUpdate(function(res) {
						// 请求完新版本信息的回调
						if (res.hasUpdate) {
							uni.showModal({
								title: '更新提示',
								content: '检测到新版本，是否下载新版本并重启小程序',
								success: function(res) {
									if (res.confirm) {
										// 用户确定更新小程序，小程序下载和更新静默进行
										self.downLoadAndUpdate(updateManager);
									} else if (res.cancel) {
										uni.showModal({
											title: '提示',
											content: '本次版本更新涉及到新功能的添加，旧版本将无法正常使用',
											showCancel: false,
											// 隐藏取消按钮
											confirmText: '确认更新',
											// 只保留更新按钮
											success: function(res) {
												if (res.confirm) {
													// 下载新版本，重启应用
													self.downLoadAndUpdate(updateManager);
												}
											}
										});
									}
								}
							});
						}
					});
				} else {
					uni.showModal({
						title: '提示',
						content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试'
					});
				}
			},

			// 下载小程序最新版本并重启
			downLoadAndUpdate: function(updateManager) {
				uni.showLoading(); // 静默下载更新小程序新版本，onUpdateReady：当新版本下载完成回调
				updateManager.onUpdateReady(function() {
					uni.hideLoading(); // applyUpdate：强制当前小程序应用上新版本并重启
					updateManager.applyUpdate();
				}); // onUpdateFailed：当新版本下载失败回调
				updateManager.onUpdateFailed(function() {
					uni.hideLoading({
						success: (res) => {
							// 下载新版本失败
							uni.showModal({
								title: '已有新版本',
								content: '新版本已经上线了，请删除当前小程序，重新搜索打开',
								showCancel: false // 隐藏取消按钮
							});
						}
					});
				});
			}
		}
	};
</script>
<style>
	/**app.wxss**/
	@import url("@/static/iconfont/iconfont.css");
	@import './common/style/flex.css';

	page {
		background-color: #f5f7fb;
	}
	
	/* App.vue 或全局样式文件 styles/global.css */
	/* 印尼要求字体文件 */
	@font-face {
	  font-family: 'TelkomselBatikSans-Regular';
	  src: url('~@/static/fonts/TelkomselBatikSans-Regular.ttf') format('truetype'); 
	  font-weight: normal;
	  font-style: normal;
	}
	 
	/* 应用全局字体 */
	body {
	  font-family: 'TelkomselBatikSans-Regular', sans-serif;
	}

	.container {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		padding: 200rpx 0;
		box-sizing: border-box;
	}

	.bottom-fixed {
		position: fixed;
		bottom: 0;
		left: 0;
		width: calc(100% - 40rpx);
		display: flex;
		justify-content: center;
		align-items: center;
		text-align: center;
		color: #999999;
		padding: 20rpx 20rpx 40rpx 20rpx;
	}

	.empty {
		width: 100vw;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #999999;
		text-align: center;
		font-size: 24rpx;
	}

	.form {
		width: auto;
	}

	.form-item {
		padding: 0 0 20rpx 0;
	}

	.form-control,
	.picker {
		background: #ffffff;
		padding: 20rpx;
		border-radius: 10rpx;
	}

	.input-control {
		display: inline-block;
		padding: 16rpx 20rpx;
		background: #f6f6f6;
		border-radius: 10rpx;
	}

	.button-jf {
		border: 1rpx solid #FF0025;
		color: #FF0025;
		font-size: 24rpx;
		line-height: 2.3;
		border-radius: 10rpx;
	}

	.button-jf:link {
		background: #FFFFFF;
	}

	.button-jf:visited {
		background: #FFFFFF;
	}

	.button-jf:hover {
		background: #FFFFFF;
	}

	.button-jf:active {
		background: #ECFBFA;
	}

	.button-jf.block {
		width: 100% !important;
	}

	.foot-button {
		position: fixed;
		bottom: 50rpx;
		width: 100%;
	}

	button.block {
		/* width: 100% !important; */
		width: 100%;
	}

	button[type='primary'] {
		background-color: #FF0025 !important;
		color: #fff !important;
		/* width: 96% !important; */
	}

	button[type='primary'].button-hover {
		background-color: #B90024 !important;
	}

	button[plain][type='primary'] {
		background-color: transparent !important;
		color: #FF0025 !important;
		border: 1rpx solid #FF0025 !important;
	}

	button[plain][type='primary'].button-hover {
		background-color: #d8fffd !important;
	}

	button[disabled][type='primary'] {
		background-color: #b1d8d6 !important;
		color: #75a7a5 !important;
	}

	button[type='operation'] {
		color: #FF0025 !important;
		background-color: #fff !important;
		border: 1rpx solid #B9B9B9 !important;
		width: 96%;
	}

	button[type='operation'].button-hover {
		background-color: #B90024 !important;
	}

	button[type='warn'] {
		background-color: #f95151 !important;
		color: #fff !important;
	}

	button[type='warn'].button-hover {
		background-color: #e24a4a !important;
	}

	button[plain][type='warn'] {
		background-color: transparent !important;
		color: #f95151 !important;
		border: 1rpx solid #f95151 !important;
	}

	button[type='delete'] {
		color: #f95151 !important;
		background-color: #fff !important;
		border: 1rpx solid #B9B9B9 !important;
		width: 96% !important;
	}

	button[plain][type='warn'].button-hover {
		background-color: #f9f6f6 !important;
	}

	button[disabled][type='warn'] {
		background-color: #e7b5b5 !important;
		color: #c28a8a !important;
	}
    button::after {
		border: none;
	}
	/* 主色 */
	.color-primary {
		color: #FF0025;
	}

	.color-

	/* 默认字号 */
	.font-default {
		font-size: 30rpx;
	}

	/* 图标 */
	/* xs,sm,lg,xl,xxl,xxxl */
	.icon-xs {
		width: 22rpx;
		height: 22rpx;
		margin: 0 6rpx;
	}

	.icon-sm {
		width: 42rpx;
		height: 42rpx;
		margin: 0 6rpx;
	}

	.icon-lg {
		width: 64rpx;
		height: 64rpx;
	}

	.icon-xl {
		width: 96rpx;
		height: 96rpx;
	}

	.icon-xxl {
		width: 160rpx;
		height: 160rpx;
	}

	.cell-icons {
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
